package app.maker.controleur;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import app.maker.entity.User;
import app.maker.error.UserException;
import app.maker.service.UserService;

/**
 * Servlet implementation class UserUpdateControleur
 */
public class UserUpdateControleur extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserUpdateControleur() {
		super();
		userService = new UserService();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User user = new User();
		user.setNom(request.getParameter("nom"));
		user.setPrenom(request.getParameter("prenom"));
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		try {
			date = dateFormat.parse(request.getParameter("dateArrive")
					.toString());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		user.setDateArrivee(date);
		user.setAdresse(request.getParameter("adresse"));
		user.setEmail(request.getParameter("email"));
		user.setFonction(request.getParameter("fonction"));
		user.setSalaire(Float.parseFloat(request.getParameter("salaire")));
		user.setRole(Integer.parseInt(request.getParameter("role")));
		user.setLogin(request.getParameter("login"));
		user.setMotDePasse(request.getParameter("mdp"));
		user.setId(Integer.parseInt(request.getParameter("id")));
		user.setPhoto("maker/photos/employe.png");
		user.setRole(Integer.parseInt(request.getParameter("role")));
		user.setStatut(Byte.parseByte(request.getParameter("statut")));
		String action = request.getParameter("action");
		try {
			if (action != null && action.equals("delete"))
				userService.delete(user);
			else
				userService.update(user);
			response.sendRedirect(request.getContextPath()
					+ "/maker/admin/espace-utilisateurs.jsp");
		} catch (UserException e) {
			e.printStackTrace();
		}
	}
}
